//
//  RXFrameTabViewController.m
//  RXFrame
//
//  Created by srxboys on 2021/4/20.
//

#import "RXFrameTableViewController.h"
#import <RXFrame/RXObjNotNil.h>

@interface RXFrameTableViewController ()
@property (nonatomic, assign) CGRect tFrameVar;
@property (nonatomic, assign) BOOL isShowingKeyboard;
@end

@implementation RXFrameTableViewController
@synthesize tableView = _tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    RX_NOTI_ADD_OBNAME(@selector(onKeyboardWillShow:), UIKeyboardWillShowNotification);
    RX_NOTI_ADD_OBNAME(@selector(onKeyboardWillHide:), UIKeyboardWillHideNotification);;
    self.cellBaseHeight = 50;
}

#pragma mark - tableView
- (UITableView *)tableView {
    if(!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [self configTableView];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (BOOL)keyboardShow {
    return self.isShowingKeyboard;
}

- (void)setTableStyleGrouped {
    if(!_tableView && _tableView.style == UITableViewStylePlain) {
        //移除对象
        [_tableView removeFromSuperview];
        //新的tableView
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [self configTableView];
        [self.view addSubview:_tableView];

        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.001)];
        view.backgroundColor = [UIColor redColor];
        _tableView.tableHeaderView = view;
    }
}

- (void)configTableView {
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.backgroundColor = [UIColor clearColor];

    //header footer 默认没有
    _tableView.sectionHeaderHeight = 0;
    _tableView.sectionFooterHeight = 0;
    //自动计算高度 关闭
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;

    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 如果需要 controller.veiw 铺满 nav 和 tabbar的位置，需要设置下面
//    if (@available(iOS 11.0, *)) {
//        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }


    _tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
}

- (void)setTableViewContentInsetTopIsZero {
    UIEdgeInsets inset = self.tableView.contentInset;
    inset.top = 0;
    self.tableView.contentInset = inset;
}

- (void)setTableViewContentOutside {
    UIEdgeInsets inset = self.tableView.contentInset;
    inset.bottom = 40;
    self.tableView.contentInset = inset;
}

- (void)setTableViewHaveHeaderView {
    _tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
}
- (void)setTableViewHaveFooterView {
    _tableView.sectionFooterHeight = UITableViewAutomaticDimension;
}

// section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// row
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.cellBaseHeight;
}


#pragma mark - requestListAPI

- (NSArray *)dataListArray {
    if(!_dataListArray) {
        _dataListArray = RXCREATE_ALLOC(NSArray);
    }
    return _dataListArray;
}

- (NSDictionary *)parameterts
{
    if(!RXDictBool(_parameterts)) {
        _parameterts = @{};
    }
    return _parameterts;
}


- (Class)modelClass
{
    return _modelClass;
}


- (void)refresh {
    self.currentPage = 0;
//    self.dataListArray = nil;
    //MJ...

    [self loadMore];
}

- (void)loadMore {
    if(!RXStrBool(self.method)) return;

//    MBProgressHUD * hud;
//    if(RXStrBool(self.loadingText)) {
//        hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//        [hud showHudLoading:self.loadingText];
//    }
//
//    NSMutableDictionary *param = RXCREATE_ALLOC(NSMutableDictionary);
//    [param addEntriesFromDictionary:self.parameterts];
//    //    [param setObject:@"page" forKey:@(self.currentPage+1)];
//
//    weak(weakSelf);
//    [self RequestType:self.requestType method:self.method className:self.modelClass paramsDict:param successBlock:^(Response *responseObject) {
//        [hud hiddenHud];
//        if(responseObject.status) {
//            weakSelf.dataListArray = [weakSelf.dataListArray arrayByAddingObjectsFromArray:responseObject.content];
//            [weakSelf.tableView reloadData];
//            //            weakSelf.currentPage = ??
//        }
//    } failureBlock:^(NSError *error) {
//        [hud hiddenHud];
//    }];
}







#pragma mark - keyboard
- (void)onKeyboardWillShow:(NSNotification *)notification
{
    self.isShowingKeyboard = YES;

    NSArray *cells = [self.tableView visibleCells];
    UITableViewCell *firstResponderCell = nil;
    for (UITableViewCell *cell in cells) {
        for (UIView *view in cell.contentView.subviews) {
            if ([view isKindOfClass:[UITextField class]] && [(UITextField *)view isFirstResponder]) {
                firstResponderCell = cell;
                break;
            }
        }
    }

    if (firstResponderCell == nil)
        return ;

    __weak typeof(self) weakSelf = self;

    NSNumber *duration = [notification.userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey];
    NSValue *valueRectEnd = [notification.userInfo objectForKey: UIKeyboardFrameEndUserInfoKey];
    CGRect  keyboardRect = [valueRectEnd CGRectValue];
    CGRect  selfRect = [self.view convertRect:self.tableView.frame toView:nil];

    if (CGRectEqualToRect(self.tFrameVar, CGRectZero)) {
        self.tFrameVar = self.tableView.frame;
    }

    CGFloat tableViewNewHeight = floor(keyboardRect.origin.y - selfRect.origin.y);
    CGRect changedFrame = CGRectMake(weakSelf.tFrameVar.origin.x, weakSelf.tFrameVar.origin.y, weakSelf.tFrameVar.size.width, tableViewNewHeight);

    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:[duration floatValue] animations:^{
            weakSelf.tableView.frame = changedFrame;

        } completion:^(BOOL finished) {

            if (firstResponderCell) {
                NSIndexPath *indexPath = [weakSelf.tableView indexPathForCell:firstResponderCell];
                [weakSelf.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
            }
        }];
    });
}

- (void)onKeyboardWillHide:(NSNotification *)notification
{
    self.isShowingKeyboard = NO;

    if (CGRectEqualToRect(self.tFrameVar, CGRectZero))
        return ;

    NSNumber *duration = [notification.userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey];

    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{

        [UIView animateWithDuration:[duration floatValue] animations:^{
            if (!CGRectEqualToRect(self.tFrameVar, CGRectZero)){
                weakSelf.tableView.frame = weakSelf.tFrameVar;
            }
        } completion:^(BOOL finished) {
            if (finished && !weakSelf.isShowingKeyboard)
                weakSelf.tFrameVar = CGRectZero;
        }];
    });
}

- (void)tabBarItemDoubleClick {
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)dealloc {
    RX_NOTI_REMOVE_SELF;
    RXLog(@"class %@ dealloc", SELF_CLASS_NAME);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
